package com.richest.api.controller.pay;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.github.wxpay.sdk.WXPay;
import com.richest.api.service.IEatOrderService;
import com.richest.api.service.IFoodOrderService;
import com.richest.api.service.IPayCallBackService;
import com.richest.api.service.IPayRecordService;
import com.richest.api.utils.AliAppInfo;
import com.richest.api.utils.AlipayNotifyParam;
import com.richest.api.utils.MessageUtil;
import com.richest.api.utils.WXConfigUtil;
import com.richest.api.utils.WxpayNotifyParam;
import com.richest.bean.EatOrderBean;
import com.richest.bean.PayCallBackBean;
import com.richest.bean.PayRecordBean;
import com.richest.util.CallResults;
import com.richest.util.UUIDGenerator;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

/**
 * 回调接口
 * 
 * @author zhaohongchao 2019年3月26日 上午8:34:52
 * @email 70375739@qq.com
 */
@Api(value = "回调接口")
@RestController
@RequestMapping("notifyController")
@EnableAutoConfiguration
public class notifyController {
	private static Logger logger = LoggerFactory.getLogger(notifyController.class);
	@Autowired
	private IPayCallBackService payCallBackService;
	@Autowired
	private IEatOrderService eatOrderSrevice;
	@Autowired
	private IPayRecordService payRecordService;
	@Autowired
	IFoodOrderService foodOrderService;

	/**
	 * 微信支付结果通知
	 * 
	 * @author 赵鸿超 2017年9月24日
	 * @param jsonObject
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "wxPayNotify")
	@ApiOperation(notes = "微信支付回调", value = "微信支付回调", httpMethod = "POST")
	@ResponseBody
	protected String wxPayNotify(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, ParseException {
		/**
		 * 支付结果通用通知回调逻辑
		 * 
		 * 当返回状态码为成功SUCCESS时，判断业务结果result_code 如果业务结果result_code为成功SUCCESS时，校验签名是否正确
		 * 如果签名验证成功，向云平台提交订单数据 如果向云平台提交数据成功，给微信返回SUCCESS,向日志表中插入数据
		 * 如果向云平台提交数据失败，给微信返回FAIL,给相关人发送模板通知，向日志表中插入数据
		 * 如果向云平台提交数据出现异常，给微信返回FAIL,给相关人发送模板通知，向日志表中插入数据
		 * 如果签名验证失败,给相关人发送模板通知，给微信返回FAIL状态码 如果签名验证出现异常,给相关人发送模板通知，给微信返回FAIL状态码
		 * 如果业务结果result_code为成功FAIL时，给相关人发送模版消息告知 当返回状态码为成功FAIL时，不做任何处理
		 */
		Map<String, String> mapRequest = new HashMap<String, String>();
		// try {
		// mapRequest = MessageUtil.parseXml(request);
		// } catch (Exception e) {
		// e.printStackTrace();
		// logger.error(e.getMessage());
		// }
		mapRequest = (Map<String, String>) JSON.parse(
				"{\"transaction_id\":\"4200000273201904095269431826\",\"nonce_str\":\"a6b1a9ae339646038cc788e5ab4a349e\",\"bank_type\":\"CFT\",\"openid\":\"oIcKq1Uh1iFzXMp2Kumz2AlMnYaI\",\"sign\":\"CC735460284FE21D616235E5EBDD34C2\",\"fee_type\":\"CNY\",\"mch_id\":\"1516500931\",\"cash_fee\":\"1\",\"out_trade_no\":\"wxpay1554790096929\",\"appid\":\"wx55a47af8ae69ae28\",\"total_fee\":\"1\",\"trade_type\":\"APP\",\"result_code\":\"SUCCESS\",\"attach\":\"1\",\"time_end\":\"20190409140825\",\"is_subscribe\":\"N\",\"return_code\":\"SUCCESS\"}");
		logger.info("微信支付结果回调" + JSON.toJSONString(mapRequest));
		String strReturnCode = mapRequest.get("return_code");// 返回状态码

		WxpayNotifyParam wxpayNotifyParam = buildWxpayNotifyParam(mapRequest);

		// 当微信返回状态码为成功FAIL时，不做任何处理
		if ("FAIL".equals(wxpayNotifyParam.getReturn_code())) {
			String strReturnMsg = mapRequest.get("return_msg");// 返回信息
			logger.debug("WX  return_msg==" + strReturnMsg);
			return "";
		}

		String strOpenId = mapRequest.get("openid");// 用户标识
		String strAppid = mapRequest.get("appid"); // 公众账号ID

		String strMchId = mapRequest.get("mch_id");// 商户号
		logger.debug("商户号 mch_id==" + strMchId);

		String strSubAppid = mapRequest.get("sub_appid");// 子商户公众账号ID
		logger.debug("子商户公众账号ID sub_appid==" + strSubAppid);

		String strSubMchId = mapRequest.get("sub_mch_id");// 子商户号
		logger.debug("子商户公众账号ID sub_mch_id==" + strSubMchId);

		String strSubOpenid = mapRequest.get("sub_openid");// 子商户用户标识
		logger.debug("子商户公众账号ID sub_openid==" + strSubAppid);
		if (null != strSubOpenid) {
			strOpenId = strSubOpenid;
		}
		String strTradeType = mapRequest.get("trade_type");// 交易类型
		String strPayPlatType = "JSAPI".equals(strTradeType) ? "WeChat_APP_Pub" : "APP";// 缴费平台
		logger.debug("交易类型 trade_type==" + strTradeType);

		String strBankType = mapRequest.get("bank_type");// 付款银行
		logger.debug("付款银行 bank_type==" + strBankType);

		String strOutTradeNo = mapRequest.get("out_trade_no");// 商户订单号
		logger.debug("商户订单号 out_trade_no==" + strOutTradeNo);

		String strAttach = mapRequest.get("attach");// 商户数据包，原样返回，空参数不传递
		logger.debug("商户数据包，原样返回，空参数不传递 strAttach==" + strAttach);

		String strTransactionId = mapRequest.get("transaction_id");// 微信支付订单号
		logger.debug("微信支付订单号 transaction_id==" + strTransactionId);

		String strTotalFeeFen = mapRequest.get("total_fee");// 金额,以分为单位
		logger.debug("金额,以分为单位 total_fee分==" + strTotalFeeFen);
		// 金额,以元为单位
		Double dTotalFee = (new BigDecimal(strTotalFeeFen)).multiply(new BigDecimal("0.01")).doubleValue();// 金额,以元为单位
		logger.debug("金额,以元为单位 total_fee元==" + dTotalFee);

		// total_fee+coupon_fee=原请求的total_fee
		String strCouponFee = mapRequest.get("coupon_fee");// 代金券或立减优惠金额
		logger.debug("代金券或立减优惠金额，coupon_fee有值 coupon_fee==" + strCouponFee);

		// total_fee+coupon_fee=原请求的total_fee
		String strTimeEnd = mapRequest.get("time_end");// 支付完成时间 time_end
		logger.debug("支付完成时间  time_end==" + strTimeEnd);

		String strResultCode = mapRequest.get("result_code");// 业务结果result_code
		logger.debug("业务结果 result_code==" + strResultCode);

		String strPayCallBackId = UUIDGenerator.generatorUUID();
		PayCallBackBean payCallBackBean = new PayCallBackBean();
		payCallBackBean.setId(strPayCallBackId);

		WXConfigUtil config = new WXConfigUtil();
		WXPay wxpay = new WXPay(config);

		// 如果微信返回的业务结果result_code为成功SUCCESS时，校验签名是否正确
		if ("SUCCESS".equals(wxpayNotifyParam.getResult_code())) {
			boolean signVerified = false;// 云端返回的签名校验结果
			try {
				signVerified = wxpay.isPayResultNotifySignatureValid(mapRequest);
			} catch (Exception e) {
				logger.error(" 校验签名过程中出现异常" + e.getMessage());
				return "fail";
			} // 4.对验签进行处理
			if (signVerified) { // 验签通过

				/**
				 * B.第一次成功的调用，插入调用日志，准备记账
				 * 
				 */
				// 修改支付完成时间的格式

				payCallBackBean.setId(strPayCallBackId);
				payCallBackBean.setApp_id(wxpayNotifyParam.getAppid());
				payCallBackBean.setBuyer_id(wxpayNotifyParam.getOpenid());
				payCallBackBean.setCallback_ret(wxpayNotifyParam.getResult_code());
				if ("SUCCESS".equals(wxpayNotifyParam.getResult_code())) {
					payCallBackBean.setCallback_ret_desc("成功");
				} else {
					payCallBackBean.setCallback_ret_desc("失败");
				}

				payCallBackBean.setCreate_by("FIRST");
				payCallBackBean.setCreate_time(new Date());

				SimpleDateFormat df1 = new SimpleDateFormat("yyyyMMddHHmmss");
				payCallBackBean.setGmt_payment(df1.parse(wxpayNotifyParam.getTime_end()));
				payCallBackBean.setMch_id(wxpayNotifyParam.getMch_id());
				payCallBackBean.setPay_params(wxpayNotifyParam.getAttach());
				payCallBackBean.setNotify_time(new Date());
				payCallBackBean.setOut_trade_no(wxpayNotifyParam.getOut_trade_no());
				payCallBackBean
						.setTotal_fee(new BigDecimal(wxpayNotifyParam.getTotal_fee()).multiply(new BigDecimal("0.01")));
				payCallBackBean.setPay_way("Wxpay");
				payCallBackBean.setEat_serial_number(wxpayNotifyParam.getOut_trade_no());
				payCallBackBean.setOpen_id(wxpayNotifyParam.getOpenid());
				payCallBackBean.setAttach(wxpayNotifyParam.getAttach());
				payCallBackBean.setTransaction_id(wxpayNotifyParam.getTransaction_id());
				payCallBackBean.setResult_code(wxpayNotifyParam.getResult_code());
				payCallBackService.insertOrUpdate(payCallBackBean);

				/**
				 * C.保存支付记录
				 * 
				 */
				PayRecordBean payRecordBean = new PayRecordBean();
				payRecordBean.setAdmart_id(Long.valueOf(wxpayNotifyParam.getAttach()));
				payRecordBean.setCreate_by("progrom");
				payRecordBean.setCreate_time(new Date());
				payRecordBean.setEat_serial_number(wxpayNotifyParam.getOut_trade_no());
				payRecordBean.setPay_callback_id(strPayCallBackId);
				payRecordBean.setPay_mode("02");
				payRecordBean.setPay_mode_name("支付宝支付");
				payRecordBean
						.setTotal_fee(new BigDecimal(wxpayNotifyParam.getTotal_fee()).multiply(new BigDecimal("0.01")));
				payRecordBean.setStatus(1);
				payRecordBean.setStatus_name("支付");
				payRecordBean.setTrade_type("APP");
				payRecordService.insert(payRecordBean);

				/**
				 * D 更新订单表，结算订单
				 */
				JSONObject orderParams = new JSONObject();
				orderParams.put("pay_callback_id", strPayCallBackId); // 回调记录ID
				orderParams.put("pay_callback_table_name", "sys_pay_callback"); // 回调记录表名
				orderParams.put("eat_serial_number", wxpayNotifyParam.getOut_trade_no()); // 商户数据包，业务发生时封装的参数，原样不动
				orderParams.put("open_id", wxpayNotifyParam.getOpenid());
				orderParams.put("pay_mode", "03");
				orderParams.put("receipt_amount", new BigDecimal(wxpayNotifyParam.getCash_fee()).multiply(new BigDecimal("0.01")));

				logger.debug(" 调用eatOrderSrevice.SettlementOrder : " + orderParams);

				String strStatus = eatOrderSrevice.SettlementOrder(orderParams);

				logger.debug("调用eatOrderSrevice.SettlementOrder 返回结果: " + strStatus);
				if (strStatus.equals("0")) {
					if ("SUCCESS".equals(wxpayNotifyParam.getResult_code())) {
						payCallBackBean.setCallback_ret_desc("完成");
					} else {
						payCallBackBean.setCallback_ret_desc("未完成");
					}
					payCallBackBean.setCallback_ret(wxpayNotifyParam.getReturn_code());
					payCallBackBean.setTrade_status("DONE");
				} else if (strStatus.equals("2")) {
					payCallBackBean.setTrade_status("FAIL");
					payCallBackBean.setCallback_ret("FAIL");
					payCallBackBean.setCallback_ret_desc("支付的金额和订单金额不同");
				} else {
					payCallBackBean.setTrade_status("FAIL");
					payCallBackBean.setCallback_ret("FAIL");
					payCallBackBean.setCallback_ret_desc("不存在有效的订单信息");
				}
				payCallBackService.insertOrUpdate(payCallBackBean);
				logger.debug("支付成功！");
				return "success";

			} else {
				payCallBackBean.setTrade_status("FAIL");
				payCallBackBean.setCallback_ret("FAIL");
				payCallBackBean.setCallback_error("验签错误");
				payCallBackService.insertOrUpdate(payCallBackBean);
				logger.error("验签错误！");
				logger.error(AlipaySignature.getSignCheckContentV1(mapRequest));
				return "fail";
			}
		} else {
			payCallBackBean.setTrade_status("FAIL");
			payCallBackBean.setCallback_ret(wxpayNotifyParam.getResult_code());
			payCallBackBean.setCallback_ret_desc("支付失败");
			payCallBackService.insertOrUpdate(payCallBackBean);
			logger.debug("支付失败！");
			return "fail";
		}
	}

	@RequestMapping(value = "wxRefundNotify")
	@ApiOperation(notes = "微信退款回调", value = "微信退款回调", httpMethod = "POST")
	@ResponseBody
	protected String wxRefundNotify(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/**
		 * 支付结果通用通知回调逻辑
		 * 
		 * 当返回状态码为成功SUCCESS时，判断业务结果result_code 如果业务结果result_code为成功SUCCESS时，校验签名是否正确
		 * 如果签名验证成功，向云平台提交订单数据 如果向云平台提交数据成功，给微信返回SUCCESS,向日志表中插入数据
		 * 如果向云平台提交数据失败，给微信返回FAIL,给相关人发送模板通知，向日志表中插入数据
		 * 如果向云平台提交数据出现异常，给微信返回FAIL,给相关人发送模板通知，向日志表中插入数据
		 * 如果签名验证失败,给相关人发送模板通知，给微信返回FAIL状态码 如果签名验证出现异常,给相关人发送模板通知，给微信返回FAIL状态码
		 * 如果业务结果result_code为成功FAIL时，给相关人发送模版消息告知 当返回状态码为成功FAIL时，不做任何处理
		 */
		Map<String, String> mapRequest = new HashMap<String, String>();
		try {
			mapRequest = MessageUtil.parseXml(request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		logger.info("退款结果回调" + JSON.toJSONString(mapRequest));
		return "SUCCESS";
	}

	/**
	 * 支付宝支付成功后.回调该接口
	 * 
	 * @author zhaohongchao 2019年3月26日 下午3:51:38
	 * @email 70375739@qq.com
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "aliPayNotify")
	@ApiOperation(notes = "支付宝回调", value = "支付宝回调", httpMethod = "POST")
	@ResponseBody
	public String aliPayNotify(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String strPayCallBackId = UUIDGenerator.generatorUUID();
		// 获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map<String, String[]> requestParams = request.getParameterMap();

		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		// 1.从支付宝回调的request域中取值
		AlipayNotifyParam alipayNotifyParam = buildAlipayNotifyParam(params);
		String strCallbackRet = "";

		// 2.封装必须参数
		logger.info(JSON.toJSONString(params));

		/**
		 * A. 判断回调日志，如果存在，直接返回成功。
		 */
		PayCallBackBean payCallBackBean = payCallBackService.findAllByOutTradeNo(alipayNotifyParam.getOutTradeNo());
		if (payCallBackBean != null) {
			return "success";
		}
		payCallBackBean = new PayCallBackBean();
		// 3.签名验证(对支付宝返回的数据验证，确定是支付宝返回的)
		boolean signVerified = false;
		try {
			// 3.1调用SDK验证签名
			signVerified = AlipaySignature.rsaCheckV1(params, AliAppInfo.getAliPayPublicKey(), AliAppInfo.getCharSet(),
					AliAppInfo.getSignType());
			logger.info("验签结果：" + signVerified);
		} catch (AlipayApiException e) {
			logger.error(e.getMessage());
		}
		// 4.对验签进行处理
		if (signVerified) { // 验签通过
			if (alipayNotifyParam.getTradeStatus().equals("TRADE_SUCCESS")) { // 只处理支付成功的订单: 修改交易表状态,支付成功
				String strEatSerialNumber = alipayNotifyParam.getOutTradeNo();
				Long lAdmartId = Long.parseLong(alipayNotifyParam.getPassbackParams()); // 商户id

				/**
				 * B.第一次成功的调用，插入调用日志，准备记账
				 * 
				 */
				// 修改支付完成时间的格式

				payCallBackBean.setId(strPayCallBackId);
				payCallBackBean.setApp_id(alipayNotifyParam.getAppId());
				payCallBackBean.setBuyer_id(alipayNotifyParam.getBuyerLogonId());
				payCallBackBean.setCallback_ret(alipayNotifyParam.getTradeStatus());
				if ("TRADE_SUCCESS".equals(alipayNotifyParam.getTradeStatus())) {
					payCallBackBean.setCallback_ret_desc("成功");
				} else {
					payCallBackBean.setCallback_ret_desc("失败");
				}

				payCallBackBean.setCreate_by("FIRST");
				payCallBackBean.setCreate_time(new Date());
				payCallBackBean.setGmt_payment(alipayNotifyParam.getGmtCreate());
				// payCallBackBean.setMch_id(strMchId);
				payCallBackBean.setPay_params(alipayNotifyParam.getPassbackParams());
				payCallBackBean.setNotify_time(new Date());
				payCallBackBean.setOut_trade_no(alipayNotifyParam.getOutTradeNo());
				payCallBackBean.setPay_userid(alipayNotifyParam.getBuyerId());
				payCallBackBean.setTotal_fee(alipayNotifyParam.getTotalAmount());
				payCallBackBean.setPay_way("AliPay");
				payCallBackBean.setEat_serial_number(strEatSerialNumber);
				payCallBackBean.setOpen_id(alipayNotifyParam.getBuyerId());
				payCallBackBean.setAttach(alipayNotifyParam.getPassbackParams());
				payCallBackBean.setTransaction_id(alipayNotifyParam.getOutTradeNo());
				payCallBackBean.setResult_code(alipayNotifyParam.getTradeStatus());
				payCallBackService.insertOrUpdate(payCallBackBean);

				/**
				 * C.保存支付记录
				 * 
				 */
				PayRecordBean payRecordBean = new PayRecordBean();
				payRecordBean.setAdmart_id(lAdmartId);
				payRecordBean.setCreate_by("progrom");
				payRecordBean.setCreate_time(new Date());
				payRecordBean.setEat_serial_number(strEatSerialNumber);
				payRecordBean.setPay_callback_id(strPayCallBackId);
				payRecordBean.setPay_mode("02");
				payRecordBean.setPay_mode_name("支付宝支付");
				payRecordBean.setTotal_fee(alipayNotifyParam.getTotalAmount());
				payRecordBean.setStatus(1);
				payRecordBean.setStatus_name("支付");
				payRecordBean.setTrade_type("QUICK_MSECURITY_PAY");
				payRecordService.insert(payRecordBean);

				/**
				 * D 更新订单表，结算订单
				 */
				JSONObject orderParams = new JSONObject();
				orderParams.put("pay_callback_id", strPayCallBackId); // 回调记录ID
				orderParams.put("pay_callback_table_name", "sys_pay_callback"); // 回调记录表名
				orderParams.put("eat_serial_number", alipayNotifyParam.getOutTradeNo()); // 商户数据包，业务发生时封装的参数，原样不动
				orderParams.put("open_id", alipayNotifyParam.getBuyerId());
				orderParams.put("pay_mode", "03");
				orderParams.put("receipt_amount", alipayNotifyParam.getReceiptAmount());

				logger.debug(" 调用eatOrderSrevice.SettlementOrder : " + orderParams);

				String strStatus = eatOrderSrevice.SettlementOrder(orderParams);

				logger.debug("调用eatOrderSrevice.SettlementOrder 返回结果: " + strStatus);
				if (strStatus.equals("0")) {
					if ("TRADE_SUCCESS".equals(alipayNotifyParam.getTradeStatus())) {
						payCallBackBean.setCallback_ret_desc("完成");
					} else {
						payCallBackBean.setCallback_ret_desc("未完成");
					}
					payCallBackBean.setCallback_ret(alipayNotifyParam.getTradeStatus());
					payCallBackBean.setTrade_status("DONE");
				} else if (strStatus.equals("2")) {
					payCallBackBean.setTrade_status("FAIL");
					payCallBackBean.setCallback_ret("FAIL");
					payCallBackBean.setCallback_ret_desc("支付的金额和订单金额不同");
				} else {
					payCallBackBean.setTrade_status("FAIL");
				}
				payCallBackService.insertOrUpdate(payCallBackBean);
				logger.debug("支付成功！");
				return "success";
			} else {
				payCallBackBean.setTrade_status("FAIL");
				payCallBackBean.setCallback_ret(alipayNotifyParam.getTradeStatus());
				payCallBackBean.setCallback_ret_desc("支付失败");
				payCallBackService.insertOrUpdate(payCallBackBean);
				logger.debug("支付失败！");
				return "fail";
			}
		} else {
			payCallBackBean.setTrade_status("FAIL");
			payCallBackBean.setCallback_ret("FAIL");
			payCallBackBean.setCallback_error("验签错误");
			payCallBackService.insertOrUpdate(payCallBackBean);
			logger.error("验签错误！");
			logger.error(AlipaySignature.getSignCheckContentV1(params));
			return "fail";
		}
	}

	/**
	 * 支付宝支付成功后.通知页面
	 * 
	 * @author zhaohongchao 2019年3月26日 下午3:51:29
	 * @email 70375739@qq.com
	 * @param eatSerialNumber
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "aliPayReturn")
	@ApiOperation(notes = "支付通知", value = "支付通知", httpMethod = "POST")
	@ApiImplicitParam(name = "eatSerialNumber", value = "订单号", required = true, paramType = "query", dataType = "String")
	public CallResults returnUrl(@RequestParam String eatSerialNumber) throws UnsupportedEncodingException {
		EatOrderBean eatOrderBean = eatOrderSrevice.queryByEatSerialNumber(eatSerialNumber, null);
		return CallResults.ok().put("data", eatOrderBean.getPay_all());
	}

	// 将request中的参数转换成Map
	private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
		Map<String, String> params = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values : valueStr + values + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		return params;
	}

	private AlipayNotifyParam buildAlipayNotifyParam(Map<String, String> params) {
		String json = JSON.toJSONString(params);
		return JSON.parseObject(json, AlipayNotifyParam.class);
	}

	private WxpayNotifyParam buildWxpayNotifyParam(Map<String, String> params) {
		String json = JSON.toJSONString(params);
		return JSON.parseObject(json, WxpayNotifyParam.class);
	}
}
